package com.gl.portal.system.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.persistence.criteria.Predicate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gl.common.constant.Constants;
import com.gl.common.enums.DelFlagEnum;
import com.gl.common.enums.StatusEnum;
import com.gl.common.exception.CustomException;
import com.gl.common.util.SecurityUtils;
import com.gl.common.util.StringUtils;
import com.gl.framework.security.LoginUser;
import com.gl.framework.web.domain.TreeSelect;
import com.gl.portal.system.entity.SysDept;
import com.gl.portal.system.repository.SysDeptRepository;
import com.gl.portal.system.repository.SysUserRepository;
import com.gl.portal.system.vo.SysDeptVo;
import com.gl.portal.system.vo.SysUserVo;

/**
 * 部门服务实现类
 */
@Service
public class SysDeptService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SysDeptRepository deptRepository;

    @Autowired
    private SysUserRepository userRepository;

    /**
     * 查询部门管理数据
     *
     * @param filter 部门信息
     * @return 部门信息集合
     */
    public List<SysDeptVo> selectDeptList(SysDeptVo filter) {
        // 数据权限
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserVo user = loginUser.getUser();
        List<Long> dataScopes = loginUser.getDataScopes();
        boolean admin = SecurityUtils.isAdmin(user.getId());
        if (!admin && StringUtils.isEmpty(dataScopes)) {
            return Collections.emptyList();
        }

        return deptRepository.findAll((root, query, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.and();

            predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(root.get("isDeleted"), DelFlagEnum.OK.value()));

            if (!admin) {
                predicate = criteriaBuilder.and(predicate, root.get("id").in(dataScopes));
            }

            if (filter != null) {
                if (filter.getParentId() != null) {
                    predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(root.get("parentId"), filter.getParentId()));
                }
                if (StringUtils.isNotBlank(filter.getDeptName())) {
                    predicate = criteriaBuilder.and(predicate, criteriaBuilder.like(root.get("deptName"), "%" + filter.getDeptName() + "%"));
                }
                if (filter.getStatus() != null) {
                    predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(root.get("status"), filter.getStatus()));
                }
            }

            predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(root.get("isDeleted").as(Integer.class), 0));

            return predicate;
        }, Sort.by(Direction.ASC, "parentId", "sortNum")).stream().map(this::convert).collect(Collectors.toList());
    }

    /**
     * 数据转换
     *
     * @param entity
     * @return
     */
    private SysDeptVo convert(SysDept entity) {
        BeanCopier beanCopier = BeanCopier.create(SysDept.class, SysDeptVo.class, false);
        SysDeptVo vo = new SysDeptVo();
        beanCopier.copy(entity, vo, null);
        return vo;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    public List<SysDeptVo> buildDeptTree(List<SysDeptVo> depts) {
        List<SysDeptVo> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        for (SysDeptVo dept : depts) {
            tempList.add(dept.getId());
        }
        for (Iterator<SysDeptVo> iterator = depts.iterator(); iterator.hasNext(); ) {
            SysDeptVo dept = (SysDeptVo) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    public List<TreeSelect> buildDeptTreeSelect(List<SysDeptVo> depts) {
        List<SysDeptVo> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    public List<Long> selectDeptListByRoleId(Long roleId) {
        return deptRepository.selectDeptListByRoleId(roleId).stream().map(SysDept::getId).collect(Collectors.toList());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    public SysDeptVo selectDeptById(Long deptId) {
        Optional<SysDept> optional = deptRepository.findById(deptId);
        if (!optional.isPresent()) {
            throw new CustomException("部门数据不存在");
        }

        return this.convert(optional.get());
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    public int selectNormalChildrenDeptById(Long deptId) {
        final String SQL = "SELECT COUNT(*) FROM sys_dept WHERE `status` = 0 AND del_flag = 0 AND FIND_IN_SET(?, ancestors)";
        return jdbcTemplate.queryForObject(SQL, Integer.class, deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    public boolean hasChildByDeptId(Long deptId) {
        int result = deptRepository.countByParentIdAndIsDeleted(deptId, DelFlagEnum.OK.value());
        return result > 0 ? true : false;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    public boolean checkDeptExistUser(Long deptId) {
        int result = userRepository.countByDeptIdAndIsDeleted(deptId, DelFlagEnum.OK.value());
        return result > 0 ? true : false;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @return 结果
     */
    public String checkDeptNameUnique(SysDeptVo vo) {
        Long deptId = StringUtils.isNull(vo.getId()) ? -1L : vo.getId();
        SysDept dept = deptRepository.findByDeptNameAndParentId(vo.getDeptName(), vo.getParentId());
        if (StringUtils.isNotNull(dept) && dept.getId().longValue() != deptId.longValue()) {
            return Constants.NOT_UNIQUE;
        }
        return Constants.UNIQUE;
    }

    /**
     * 新增部门信息
     *
     * @param vo 部门信息
     * @return 结果
     */
    public void saveDept(SysDeptVo vo) {
        Optional<SysDept> optional = deptRepository.findById(vo.getParentId());
        if (!optional.isPresent()) {
            throw new CustomException("部门数据不存在");
        }
        SysDept parentDept = optional.get();

        // 如果父节点不为正常状态,则不允许新增子节点
        if (StatusEnum.NORMAL.value() != parentDept.getStatus()) {
            throw new CustomException("部门停用，不允许新增");
        }
        vo.setAncestors(parentDept.getAncestors() + "," + vo.getParentId());

        BeanCopier beanCopier = BeanCopier.create(SysDeptVo.class, SysDept.class, false);
        SysDept entity = new SysDept();
        beanCopier.copy(vo, entity, null);

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserVo user = loginUser.getUser();
        entity.setStatus(StatusEnum.NORMAL.value());
        entity.setIsDeleted(DelFlagEnum.OK.value());
        entity.setCreateUserId(user.getId());
        entity.setCreateTime(new Date());

        deptRepository.save(entity);
    }

    /**
     * 修改部门信息
     *
     * @param vo 部门信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateDept(SysDeptVo vo) {
        Optional<SysDept> newParentOptional = deptRepository.findById(vo.getParentId());

        Optional<SysDept> oldDeptOptional = deptRepository.findById(vo.getId());
        if (!oldDeptOptional.isPresent()) {
            throw new CustomException("部门数据不存在");
        }
        SysDept oldDept = oldDeptOptional.get();

        if (newParentOptional.isPresent() && StringUtils.isNotNull(oldDept)) {
            SysDept newParentDept = newParentOptional.get();
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getId();
            String oldAncestors = oldDept.getAncestors();
            vo.setAncestors(newAncestors);
            updateDeptChildren(vo.getId(), newAncestors, oldAncestors);
        }

        BeanCopier beanCopier = BeanCopier.create(SysDeptVo.class, SysDept.class, false);
        beanCopier.copy(vo, oldDept, null);

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserVo user = loginUser.getUser();
        oldDept.setUpdateUserId(user.getId());
        oldDept.setUpdateTime(new Date());
        oldDept = deptRepository.save(oldDept);

        // 如果该部门是启用状态，则启用该部门的所有上级部门
        if (StatusEnum.NORMAL.value() == vo.getStatus()) {
            this.updateParentDeptStatus(oldDept);
        }
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept) {
        String ancestors = dept.getAncestors();
        List<Long> parentIds = Arrays.asList(ancestors.split(",")).stream().map(Long::new).collect(Collectors.toList());
        List<SysDept> parentDeptList = deptRepository.findByParentIdIn(parentIds);

        parentDeptList.forEach(entity -> {
            entity.setStatus(dept.getStatus());
            entity.setUpdateUserId(dept.getUpdateUserId());
            entity.setUpdateTime(dept.getUpdateTime());
        });

        deptRepository.saveAll(parentDeptList);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptRepository.selectChildrenDeptById(deptId);

        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }

        deptRepository.saveAll(children);
    }

    /**
     * 删除部门
     *
     * @param deptId 部门ID
     * @return 结果
     */
    public void deleteDeptById(Long deptId) {
        Optional<SysDept> optional = deptRepository.findById(deptId);
        if (!optional.isPresent()) {
            throw new CustomException("部门数据不存在");
        }
        SysDept entity = optional.get();

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserVo user = loginUser.getUser();
        entity.setUpdateUserId(user.getId());
        entity.setUpdateTime(new Date());
        entity.setIsDeleted(DelFlagEnum.DELETED.value());
        deptRepository.save(entity);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDeptVo> list, SysDeptVo t) {
        // 得到子节点列表
        List<SysDeptVo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDeptVo tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                Iterator<SysDeptVo> it = childList.iterator();
                while (it.hasNext()) {
                    SysDeptVo n = (SysDeptVo) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDeptVo> getChildList(List<SysDeptVo> list, SysDeptVo t) {
        List<SysDeptVo> tlist = new ArrayList<>();
        Iterator<SysDeptVo> it = list.iterator();
        while (it.hasNext()) {
            SysDeptVo n = (SysDeptVo) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDeptVo> list, SysDeptVo t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
